package org.dfl.plugin.autoalign;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import org.dfl.messages.Messages;
import org.dfl.plugin.DflPlugin;
import org.dfl.plugin.dialogs.DialogsManager;

public class GraphvizRunner {
	static public String getString(String dotText) {
		//code based on Taverna ScuflSVGDiagram.SVGDocument()
		String dotLocation = DflPlugin.getDefault().getDotLocationPreference();
		if (dotLocation == null || dotLocation.trim().equals("")) { //$NON-NLS-1$
			dotLocation = "dot"; //$NON-NLS-1$
		}
		//logger.debug("Invoking dot...");
		Process dotProcess;
		try {
			dotProcess = Runtime.getRuntime().exec(new String[] { dotLocation, "-Tsvg" }); //$NON-NLS-1$
		} catch (Throwable ee) {
			GraphvizInstaller.installGraphviz();
			dotLocation = System.getProperty("dflplugin.dotLocation"); 
			try {
				dotProcess = Runtime.getRuntime().exec(new String[] { dotLocation, "-Tsvg" }); //$NON-NLS-1$
			} catch (Throwable e) {
				if(System.getProperty("os.name").toLowerCase().indexOf("windows")>=0){ //$NON-NLS-1$ //$NON-NLS-2$
					DialogsManager.openErrorDialog(Messages.GraphvizRunner_5);
				}else{
					DialogsManager.openErrorDialog(Messages.GraphvizRunner_6);
				}
				throw new GraphvizExecutionException(e.getLocalizedMessage());	
			}
		}
		
		StreamDevourer devourer = new StreamDevourer(dotProcess.getInputStream());
		devourer.start();
		
		// Must create an error devourer otherwise stderr fills up and the
		// process stalls!
		StreamDevourer errorDevourer = new StreamDevourer(dotProcess
				.getErrorStream());
		errorDevourer.start();

		PrintWriter out = new PrintWriter(dotProcess.getOutputStream(), true);
		out.print(dotText);
		out.flush();
		out.close();
		//String result = errorDevourer.blockOnOutput();
		String result = devourer.blockOnOutput();
		return result;
	}

	static public InputStream getStream(String dotText) {
		//code based on Taverna ScuflSVGDiagram.SVGDocument()
		String dotLocation = DflPlugin.getDefault().getDotLocationPreference();
		if (dotLocation == null || dotLocation.trim().equals("")) { //$NON-NLS-1$
			dotLocation = "dot"; //$NON-NLS-1$
		}
		//logger.debug("Invoking dot...");
		Process dotProcess;
		try {
			dotProcess = Runtime.getRuntime().exec(new String[] { dotLocation, "-Tsvg" }); //$NON-NLS-1$
		} catch (IOException ee) {
			GraphvizInstaller.installGraphviz();
			dotLocation = System.getProperty("dflplugin.dotLocation"); 
			try {
				dotProcess = Runtime.getRuntime().exec(new String[] { dotLocation, "-Tsvg" }); //$NON-NLS-1$
			} catch (Throwable e) {
				if(System.getProperty("os.name").toLowerCase().indexOf("windows")>=0){ //$NON-NLS-1$ //$NON-NLS-2$
					DialogsManager.openErrorDialog(Messages.GraphvizRunner_12);
				}else{
					DialogsManager.openErrorDialog(Messages.GraphvizRunner_13);
				}
				throw new GraphvizExecutionException(e.getLocalizedMessage());	
			}
		}
		
		// Must create an error devourer otherwise stderr fills up and the
		// process stalls!
		StreamDevourer errorDevourer = new StreamDevourer(dotProcess
				.getErrorStream());
		errorDevourer.start();

		PrintWriter out = new PrintWriter(dotProcess.getOutputStream(), true);
		out.print(dotText);
		out.flush();
		out.close();
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		StreamCopier sc = new StreamCopier(dotProcess.getInputStream(), bos);
		sc.start();
		//must join for the coping to finish
		try {sc.join();} catch (Exception e) {
			throw new GraphvizExecutionException(Messages.GraphvizRunner_14);
		}
		return new ByteArrayInputStream(bos.toByteArray());
	}
}
